package controllers;

import java.awt.event.ActionEvent;
import java.util.Vector;

import dialogs.DeleteTupleDialog;
import dialogs.InsertTupleDialog;

import models.PurchaseItemModel;

import system.View;

public class PurchaseItemController extends AbstractMenuItemController {
	private PurchaseItemModel purchase_item = new PurchaseItemModel();

	public PurchaseItemController(View v) {
		super(v);
		abstractModel = purchase_item;
		purchase_item.addExceptionListener(this);
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		String actionCommand = e.getActionCommand();

		if (actionCommand.equals("Delete Item from Purchased"))
			showDialogWindow(new DeleteTupleDialog(
					view,
					actionCommand,
					"Key",
					new String[] { "Receipt ID Number: ", "Item UPC Number: " },
					this));
		else if (actionCommand.equals("Set Item as Purchased"))
			showDialogWindow(new InsertTupleDialog(view, actionCommand,
					"Purchased Item", new String[] { "Receipt ID Number: ",
							"Item UPC Number: ", "Purchase Quantity: " }, this));
	}

	@Override
	public int validateInsert(Vector<String> s) {
		if (s.size() != 3)
			return VALIDATIONERROR;

		try {
			Integer receiptId;
			Integer upc;
			Integer quantity;

			if (s.get(0).trim().length() != 0)
				receiptId = Integer.valueOf(s.get(0).trim());
			else return VALIDATIONERROR;
			if (s.get(1).trim().length() != 0)
				upc = Integer.valueOf(s.get(1).trim());
			else return VALIDATIONERROR;
			if (s.get(2).trim().length() != 0)
				quantity = Integer.valueOf(s.get(2).trim());
			else return VALIDATIONERROR;

			view.updateStatusBar("Inserting Purchase Item...");

			if (purchase_item.insert(receiptId, upc, quantity)) 
				return operationSuccess();
			else return operationFailure();
		} catch (NumberFormatException ex) {
			return VALIDATIONERROR;
		}
	}

	@Override
	public int validateDelete(Vector<String> s) {
		if (s.size() != 2)
			return VALIDATIONERROR;

		try {
			Integer receiptId;
			Integer upc;

			if (s.get(0).trim().length() != 0)
				receiptId = Integer.valueOf(s.get(0).trim());
			else return VALIDATIONERROR;
			if (s.get(1).trim().length() != 0)
				upc = Integer.valueOf(s.get(1).trim());
			else return VALIDATIONERROR;

			view.updateStatusBar("Deleting Purchase Item...");

			if (purchase_item.delete(receiptId, upc)) return operationSuccess();
			else return operationFailure();
		} catch (NumberFormatException ex) {
			return VALIDATIONERROR;
		}
	}

}
